package org.atlantis.uzw.base.event;

import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;

public class ThreadEventHandlerScanner implements BeanPostProcessor {

	private ThreadEventRouter eventRouter;

	public void setThreadEventRouter(ThreadEventRouter eventRouter) {
		this.eventRouter = eventRouter;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(final Object bean, String beanName) throws BeansException {
		ReflectionUtils.doWithMethods(ThreadEventRouter.class, new MethodCallback() {
			@Override
			public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
				EventHandler handler = method.getAnnotation(EventHandler.class);
				if (handler == null) return;
				String[] topics = handler.value();
				if (topics.length <= 0) throw new IllegalArgumentException("event handler: {} must have one topic at least");
				for (String topic : topics) {
					eventRouter.register(topic, bean, method);
				}
			}
		});
		return bean;
	}
}
